package com.zmp.kotlinnote.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.ArrayMap
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import com.zmp.kotlinnote.utils.SvgPathData
import com.zmp.kotlinnote.utils.XmlParseTools
import com.zmp.widget.dialog.ColorPickerDialog
import kotlin.math.min


/**
 *@author zmp
 *Created by zmp on 2018/12/8
 */
class MySvgView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    View(context, attrs, defStyleAttr) {
    companion object {
        const val TAG = "MySvgView"
    }

    //存储绘制结束的path
    private val drawPath = arrayListOf<SvgPathData>()
    //path截取长度
    private var pathEnd: Float = 0F
    //截取后的Path
    private var desPath = Path()

    /**
     * 每次绘制跨度
     */
    var drawStep: Float = 50f
    /**
     * 绘制速度单位毫秒
     */
    var drawSpeedTime: Long = 100L

    private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var svgList: List<SvgPathData>? = null
    private var rectF = RectF()
    private var pathMeasure = PathMeasure()
    private val gestureDetector: GestureDetector
    private val allRegion = Region()

    private var colorArray: ArrayMap<Int, Int> = ArrayMap()

    init {
        fillPaint.style = Paint.Style.FILL
        strokePaint.style = Paint.Style.STROKE
        gestureDetector = GestureDetector(getContext(), object : GestureDetector.SimpleOnGestureListener() {
            override fun onDown(e: MotionEvent): Boolean {
                isContains(e)
                return super.onDown(e)
            }
        })
    }

    private var selectedIndex: Int = -1

    private fun isContains(e: MotionEvent, isUp: Boolean = false) {
        val let = svgList?.let {
            for (i in it.indices.reversed()) {
                val region = Region()
                Log.e(TAG, "onSingleTapUp$i")
                region.setPath(it[i].path, allRegion)
                val fl = e.x / scale - dX / scale
                val f2 = e.y / scale - dY / scale
                Log.e(TAG, "onSingleTapUp$fl--$f2")
                Log.e(TAG, "onSingleTapUp$rectF")
                if (region.contains(fl.toInt(), f2.toInt())) {
                    return@let i
                }
            }
            -1
        }
        if (let != null && let != -1) {
            if (isUp) {
                if (let == selectedIndex) {
                    Log.e(TAG, "onSingleTapUp$let")
                    val colorPickerDialog = ColorPickerDialog(context)
                    colorPickerDialog.setChooseListener { color ->
                        colorArray[let] = color
                        invalidate()
                    }
                    colorPickerDialog.show()
                    selectedIndex = -1
                } else {
                    selectedIndex = -1
                }
            } else {
                Log.e(TAG, "onDown$let")
                selectedIndex = let
            }
        } else {
            selectedIndex = -1
        }
        invalidate()
    }


    fun initSvg(
        svRes: Int,
        isVector: Boolean = true,
        isCanAnimal: Boolean = false,
        isCanAgain: Boolean = false,
        againTime: Long = 1000 * 5
    ) {
        this.isCanAgain = isCanAgain
        this.isCanAnimal = isCanAnimal
        this.againTime = againTime
        removeCallbacks(runnable)
        svgList = if (isVector) XmlParseTools.parseSvgVector(context, svRes) else XmlParseTools.parseSvg(
            context,
            svRes
        )
        svgList?.let { svg ->
            val rectF1 = RectF()
            if (svg.isNotEmpty()) {
                svg[0].path.computeBounds(rectF, true)
                svg.forEach {
                    it.path.computeBounds(rectF1, true)
                    if (rectF.left > rectF1.left) {
                        rectF.left = rectF1.left
                    }
                    if (rectF.right < rectF1.right) {
                        rectF.right = rectF1.right
                    }
                    if (rectF.top > rectF1.top) {
                        rectF.top = rectF1.top
                    }
                    if (rectF.bottom < rectF1.bottom) {
                        rectF.bottom = rectF1.bottom
                    }
                }
                index = 0
                pathEnd = 0F
                drawPath.clear()
                pathMeasure.setPath(svg[index].path, true)
                postDelayed(runnable, drawSpeedTime)
                allRegion.set(rectF.left.toInt(), rectF.top.toInt(), rectF.right.toInt(), rectF.bottom.toInt())
            }
        }
    }

    private var scale: Float = 0.0f

    private var dX: Float = 0.0f

    private var dY: Float = 0.0f

    private var index: Int = 0

    var againTime: Long = 1000 * 5

    var isCanAgain: Boolean = false

    var isCanAnimal: Boolean = false

    var pauseOrRestart: Boolean = false
        set(pause) {
            if (field != pause) {
                field = pause
                if (field) {
                    removeCallbacks(runnable)
                } else {
                    removeCallbacks(runnable)
                    post(runnable)
                }
            }
        }

    //适配View大小
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        scale = min(measuredWidth / rectF.width(), measuredHeight / rectF.height())
        dX = (measuredWidth - scale * rectF.width()) / 2
        dY = (measuredHeight - scale * rectF.height()) / 2
        Log.e(TAG, "$scale---$dX--$dY")
    }

    //绘制动画逻辑
    private var runnable = object : Runnable {
        override fun run() {
            svgList?.let { svg ->
                if (pathEnd >= pathMeasure.length) {
                    val path = Path()
                    path.lineTo(0F, 0F)//解决绘制bug
                    pathMeasure.getSegment(0F, pathMeasure.length, path, true)
                    drawPath.add(SvgPathData(path, svg[index].fillColor, svg[index].strokeColor))
                    if (pathMeasure.nextContour()) {
                        pathEnd = 0F
                    } else {
                        index++
                        if (index > svg.size - 1) {
                            invalidate()
                            postDelayed({
                                if (isCanAgain) {
                                    index = 0
                                    pathEnd = 0F
                                    drawPath.clear()
                                    pathMeasure.setPath(svg[index].path, true)
                                    post(this)
                                }
                            }, againTime)
                            return
                        }
                        pathMeasure.setPath(svg[index].path, true)
                    }
                }
                pathEnd += drawStep
                invalidate()
                postDelayed(this, drawSpeedTime)
            }
        }
    }


    //绘制逻辑
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        svgList?.let { svg ->
            canvas.scale(scale, scale)
            canvas.translate(dX / scale, dY / scale)
            if (index > svg.size - 1 || !isCanAnimal) {
                for (i in svg.indices) {
                    if (selectedIndex == i) {
                        fillPaint.color = Color.CYAN
                    } else {
                        val i1 = colorArray[i]
                        fillPaint.color = i1 ?: svg[i].fillColor
                    }
                    strokePaint.color = svg[i].strokeColor
                    canvas.drawPath(svg[i].path, fillPaint)
                    canvas.drawPath(svg[i].path, strokePaint)
                }
                return
            }
            drawPath.forEach {
                strokePaint.color = Color.RED
                fillPaint.color = it.fillColor
                canvas.drawPath(it.path, fillPaint)
                canvas.drawPath(it.path, strokePaint)
            }
            desPath.reset()
            desPath.lineTo(0F, 0F)//解决绘制bug
            pathMeasure.getSegment(0F, pathEnd, desPath, true)
            strokePaint.color = Color.MAGENTA
            canvas.drawPath(desPath, strokePaint)
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_UP -> {
                isContains(event, true)
            }
            MotionEvent.ACTION_CANCEL -> {
                isContains(event, true)
            }
            else -> {
            }
        }
        gestureDetector.onTouchEvent(event)
        return true
    }

}